import { useEffect, useState } from 'react';

import commonService from '@/api/services/commonService';
import { LoginModal } from '@/components/login';

import MenuBar from './menu';
import NoticeBar from './notice';

let lastScrollTop = 0;
export default function HeaderBlock() {
  const [info, setInfo] = useState<any>({});
  const [isSticky, setIsSticky] = useState(false);

  useEffect(() => {
    commonService.getCustomApi('/common/header/getHeaderData', {}).then((res) => {
      setInfo(res);
    });
  }, []);

  useEffect(() => {
    const handleScroll = () => {
      const currentScrollTop: number = window.scrollY || document.documentElement.scrollTop;
      if (currentScrollTop > lastScrollTop && currentScrollTop > 100) {
        // 向下滚动且滚动距离大于100时，隐藏头部
        setIsSticky(false);
      } else {
        // 向上滚动或滚动距离小于等于100时，显示头部
        setIsSticky(true);
      }

      lastScrollTop = currentScrollTop;
    };

    window.addEventListener('scroll', handleScroll);
    // 组件卸载时移除事件监听器
    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);

  return (
    <div
      className={`${
        isSticky ? 'fixed' : 'absolute'
      } top-0 z-[100] mt-0 flex w-[100%] flex-col bg-[#ffffff]`}
    >
      {info.webHeadBanner ? (
        <div className="w-full bg-[#C9232E]">
          <img className="h-[50px]" src={info.webHeadBanner.picPath} alt="top banner" />
        </div>
      ) : (
        ''
      )}
      <NoticeBar notice={info.noticeList || []} active={info.activeList || []} />
      <MenuBar />
      <LoginModal />
    </div>
  );
}
